import logging
import random
from operator import and_, not_

from flask import make_response, render_template, g, request, jsonify, redirect

from info import constants, db
from info.utils.common import user_login_data
from info.models import News, Category, User
from . import index_blu

# Todo 新闻首页
@index_blu.route('/')
@user_login_data
def index():
    reldata = {}
    reldata["data"] = {}
    data = reldata["data"]
    # 获取到当前登录用户的id
    user = g.user
    # 右侧新闻排行
    # 按照点击量排序查询出点击最高的前10条新闻
    try:
        upnews = News.query.filter(News.status==0).order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS).all()
    except Exception as e:
        logging.error("Mysql数据库出错,错误原因%s"%e)
        data = {"error":"系统错误"}
        return make_response(render_template('news/500.html',**data),500)
    # 将对象字典添加到列表中
    data["user"]=user
    data["upnews"]=upnews
    # 获取新闻分类数据
    try:
        categories = Category.query.all()
    except Exception as e:
        logging.error("Mysql数据库出错,错误原因%s" % e)
        return redirect("/500.html")
    # 定义列表保存分类数据
    data["categories"] = categories
    # 返回数据
    return make_response(render_template('news/index.html',**reldata),constants.PAGE_NET_TAG)

# Todo 新闻列表
@index_blu.route('/news_list')
def news_list():
    """
    获取首页新闻数据
    :return:
    """

    # 1. 获取参数,并指定默认为最新分类,第一页,一页显示10条数据
    page = request.args.get("page","1")
    cid = request.args.get("cid","1")

    # 2. 校验参数
    try:
        page = int(page)
        cid = int(cid)
    except Exception as e:
        data = {
            "error": constants.WRONG_INPUT_TAG,
            "errmsg":"数据类型传输错误",
            "news": [],
            "total_page": 0
        }
        return jsonify({"data": data})

    # 默认选择最新数据分类

    # 3. 查询数据
    try:
        if cid == 1:
            pageinate = News.query.filter(News.status==0).order_by(News.create_time.desc()).paginate(page=page,per_page=constants.USER_COLLECTION_MAX_NEWS)
        else:
            pageinate = News.query.filter(and_(News.category_id==cid,News.status==0)).paginate(page=page,per_page=constants.USER_COLLECTION_MAX_NEWS)
    except Exception as e:
        data={
            "error":constants.SYSTEM_WRONE_TAG,
            "errmsg": "数据库错误错误原因%s"%e,
            "news":[],
            "total_page":0
        }
        return jsonify({"data":data})
    news = pageinate.items
    inews = []
    for new in news:
        inew = new.to_basic_dict()
        inews.append(inew)
    # 将模型对象列表转成字典列表
    totalPage = pageinate.pages
    #返回数据
    data = {
        "error":constants.CORRECT_TAG,
        "news_dict_list":inews,
        "total_page":totalPage
    }

    return jsonify({"data":data})

# Todo 404页面
@index_blu.route("/404.html")
@user_login_data
def page_notfind():
    data = {}
    if g.user:
        data["user"] = g.user
    return make_response(render_template('news/404.html',data=data),404)

# Todo 500页面
@index_blu.route("/500.html")
@user_login_data
def errpage():
    data = {}
    if g.user:
        data["user"] = g.user
    return make_response(render_template('news/500.html',data=data),500)










